package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private ICategoryService categoryService;


    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R pageQuery(Integer page, Integer pageSize, String name) {
        //创建page
        IPage<Dish> pageInfo = new Page<>(page, pageSize);

        //添加条件
        LambdaQueryWrapper<Dish> lqw = Wrappers.lambdaQuery(Dish.class)
                .like(StringUtils.isNotEmpty(name), Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, lqw);

        //到这里结束了?不,前端还需要传菜品分类categoryName
        //分类在category表中

        // List<Dish> records ---> List<DishDto> dishDtos

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> dishDtos = new ArrayList<>();

        log.info("拼dishDto");

        for (Dish dish : records) {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);

            //获取到了当前分类的名称
            String categoryName = category.getName();

            // 新建一个DishDto 将分类名称set进入
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);

            //还要将dish数据放进去
            BeanUtils.copyProperties(dish, dishDto);
            dishDtos.add(dishDto);

            log.info(dishDto.toString());
        }

        //这时候,传前端数据,需要 总条数total+总数据records

        Map map = new HashMap();
        map.put("total", pageInfo.getTotal());
        map.put("records", dishDtos);

        return R.success(map);//一定是map

    }


    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        log.info("get" + id);

        Dish dish = dishService.selectById(id);
        return R.success(dish);

    }

    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);
        return R.success(null);
    }


    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        log.info("执行删除操作");
        dishService.deleteByIds(ids);
        return R.success(null);
    }

    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("执行更新起售");


        dishService.updateStatus(status, ids);
        return R.success(null);
    }

    @GetMapping("/list")
    public R selectList(@RequestParam Long categoryId) {
        log.info("根据id" + categoryId + "查询分类下所有菜品");
        //R<List<DishDto>>   返回的Dish集合中还需要有菜品的口味数据  DishDto【既包含菜品数据也包含菜品的口味数据】
//        List<Dish> dishes = dishService.selectWithCategoryId(categoryId);
//        return R.success(dishes);

        List<Dish> dishes = dishService.selectWithCategoryId(categoryId);
        List<DishDto> dishDtos = dishes.stream().map((dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);

            LambdaQueryWrapper<Category> qw = Wrappers.lambdaQuery(Category.class).eq(Category::getId, categoryId).select(Category::getName);
            dishDto.setCategoryName(categoryService.getOne(qw).getName());

            LambdaQueryWrapper<DishFlavor> qw2 = Wrappers.lambdaQuery(DishFlavor.class).eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> list = dishFlavorService.list(qw2);
            dishDto.setFlavors(list);

            return dishDto;
        })).collect(Collectors.toList());

        return R.success(dishDtos);
    }

}
